package Design_patterns.creator_mode.factory.extendedMode;

import Design_patterns.creator_mode.factory.extendedMode.config_factory.Coffee;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

/**
 * @description: 咖啡工厂类
 **/

public class CoffeeFactory {

    //加载配置文件，获取配置文件中配置的全类名，并创建该类对象存储起来
    //1.定义容器对象存储咖啡对象
    private static HashMap<String, Coffee> map = new HashMap<>();

    //2.加载配置文件，只需要加载一次
    static {
        //2.1 创建properties对象
        Properties properties = new Properties();
        //2.2 调用properties对象中的load方法进行配置文件的加载
        //获取位置
        InputStream inputStream =
                CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(inputStream);
            // 从properties中获取全类名并创建对象
            Set<Object> objects = properties.keySet();
            for (Object key : objects) {
                String className = properties.getProperty((String) key);
                //通过反射技术创建对象
                Class<?> clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                //将名称和对象存储到容器中
                map.put((String) key, coffee);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    //根据名称获取方法
    public static Coffee createCoffee(String name) {
        return map.get(name);
    }
}
